package zhoug.common.http.ssl;

import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.List;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import androidx.annotation.Nullable;

/**
 * 信任管理器工厂
 * 创建信任的服务器证书管理器
 * @Author 35574
 * @Date 2021/10/12
 * @Description
 */
public class ZTrustManagerFactory {


    /**
     * 根据证书生成信任管理器数组 ,KeyStore去引导生成的TrustManager
     * @param aliasList 证书别名列表
     * @param certificates 证书列表
     * @return
     */
    public static TrustManager[] getTrustManagers(@Nullable List<String> aliasList,  List<Certificate> certificates){
        if(certificates==null){
            return null;
        }
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null,null);
            String alias=null;
            for (int i = 0; i < certificates.size(); i++) {
                if(aliasList!=null && aliasList.size()==certificates.size()){
                    alias=aliasList.get(i);
                }else{
                    alias="as"+i;
                }
                keyStore.setCertificateEntry(alias,certificates.get(i));
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
          return  trustManagerFactory.getTrustManagers();
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }



}
